package mfuny.ggongal.admin.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import org.springframework.web.multipart.MultipartFile;

public class HttpPostSender {
	
	public String send(String url, HashMap<String, String> params, String encode) throws Exception {
		
		URL targetURL = new URL(url);
		HttpURLConnection httpConn = (HttpURLConnection)targetURL.openConnection();
		httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		httpConn.setRequestMethod("POST");
		httpConn.setDoOutput(true);
		httpConn.setDoInput(true);
		httpConn.setUseCaches(false);
		httpConn.setDefaultUseCaches(false);
		
		String paramStr = null;
		Iterator<Entry<String, String>> it = params.entrySet().iterator();
		while( it.hasNext() ) {
			Entry<String, String> en = (Entry<String, String>) it.next();
			if( paramStr == null ) {
				paramStr = URLEncoder.encode(en.getKey(), encode) + "=" + URLEncoder.encode(en.getValue(), encode);
			} else {
				paramStr += "&" + URLEncoder.encode(en.getKey(), encode) + "=" + URLEncoder.encode(en.getValue(), encode);
			}
		}
		
		OutputStream os = httpConn.getOutputStream();
		os.write(paramStr.getBytes());
		os.flush();
		os.close();
		
		String buffer = null;
		String result = "";
		BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
		
		while( (buffer = br.readLine()) != null ) {
			result += buffer;
		}
		br.close();
		
		return result;
	}
	
	//서버정보 ( url, saveName, savePath).
	public String sendFile( String[] url, HashMap<String, Object> fileInfo, MultipartFile file) {
		URL targetURL = null;
		HttpURLConnection httpConn = null;
		
		try {
			for( String urlStr : url ) {
				targetURL = new URL( urlStr );
				httpConn = (HttpURLConnection)targetURL.openConnection();
				httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				httpConn.setRequestMethod("POST");
				httpConn.setDoOutput(true);
				httpConn.setDoInput(true);
				httpConn.setUseCaches(false);
				httpConn.setDefaultUseCaches(false);
			}
		} catch ( Exception e ) {
			
		}
		
		
		return null;
	}
}
